<!--
 * @Description: 
 * @Author: 张文韬
 * @Date: 2024-06-24 15:29:13
 * @LastEditTime: 2024-07-16 14:09:13
 * @LastEditors: 张文韬
 * @Reference: 
-->
<template>
  <div class="flex flex-items-center">
    <label>投保人信息</label>
    <el-radio-group v-model="type" class="ml-4" @change="changeType">
      <el-radio value="2" size="large">自动</el-radio>
      <el-radio value="1" size="large">个人投保</el-radio>
      <el-radio value="0" size="large">企业投保</el-radio>
    </el-radio-group>
    <span class="ml-10px text-red">如需开具发票,发票抬头需与投保企业一致</span>
    <el-button v-if="type == '0'" class="ml-10px" type="primary" @click="handleRecord">历史记录</el-button>
  </div>
  <!-- v-if="type == 2" -->
  <e-table
    v-if="type!=2"
    :data="tableData"
    :columns="showColumns"
    :pageData="pageInfo"
    :loading="loading"
  > 
    <template #certificateType="{ scope }">
      <dict-tag :options="type==1?certificate_type:certificate_type_tuan" :value="scope.row.certificateType"></dict-tag>
    </template>
    <template #handleSlot="{scope}">
      <el-button type="warning" @click="edit(scope.row)" size="small">编辑</el-button>
      <el-button type="danger" @click="remove(scope.$index)" size="small">删除</el-button>
    </template>
    <template #empty>
      <el-button type="success" @click="insert">添加</el-button>
    </template>
  </e-table>
  <!-- <el-form 
    v-if="type == 3"
    :inline="true" 
    :model="formData">
    <el-form-item label="企业名称" required>
      <div class="flex gap-10px">
        <el-input v-model="formData.company" placeholder="请输入企业名称" clearable />
        <el-button type="primary" @click="getTaxNumber">获取税号</el-button>
      </div>
    </el-form-item>
    <el-form-item label="企业代码" required>
      <el-input v-model="formData.company" placeholder="请输入企业代码" clearable />
    </el-form-item>
  </el-form> -->
  <el-dialog
    v-model="dialogShow"
    :ref="dialogTitle"
    :width="800"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <template v-if="dialogShow">
      <CompanyHolder v-if="dialogType == 'company-record'" ref="companyHolderRef" />
      <EForm
        v-else
        class="mr-10px"
        ref="dialogForm"
        :form-options="formOptions"
        form-label-width="120px"
        :form-rules="editFormRules"
        :form-data-current="dialogFormCurrent"
        @cardTypeChange="changeCardType"
        @cardNumberChange="changeCardNumber"
      ></EForm>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

import { editFormOptions, editFormRules } from '../Insurant/form'
import eTable from '@/components/e-table'
import CompanyHolder from '../CompanyHolder/index.vue'
import config from './config'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus';
import idCardTool from "@/utils/id-card";
import EForm from '/@/components/e-form/e-form.vue';
import { personCertificateTypes, companyCertificateTypes } from '/@/utils/constants'
import { useDict } from '/@/hooks/dict';

let defaultCardType = '01'

const emits = defineEmits(['policyHolderTypeChange'])

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  dataSource: {
    type: Object,
    default: () => {}
  },
  columns: {
    type: Array,
    default: () => []
  },
  pageInfo: {
    type: Object,
    default: () => ({
      pageShow:false,
      total: 0,
      currentPage: 1,
      pageSize: 10
    })
  },
  // autoPolicy: {
  //   type: Boolean,
  //   default: true
  // }
})

const { certificate_type, certificate_type_tuan } = useDict('certificate_type', 'certificate_type_tuan');

const formOptions = ref(config.editFormOptions.slice(0, config.editFormOptions.length - 1))

const loadData = async () => {
	formOptions.value.forEach((item) => {
		if (item.key == 'certificateType') {
			item.options = certificate_type;
		}
	});
};
loadData();

const type = ref('2')

const showColumns = computed(() => {
  if (type.value == '0') {
    return config.columns.filter(o => !['birthday', 'sexCode'].includes(o.prop))
  }
  return config.columns.filter(o => o.prop != 'relationshipWithApplicant')
})

const tableData = ref([])

const dialogForm = ref(null)
const dialogShow = ref(false)
const dialogType = ref('person') 
const dialogFormCurrent = ref()
const dialogTitle = computed(() => {
  if (type.value < 2) {
    return '投保人信息'
  }
  else if (type.value == 3) {
    return '获取税号'
  }
})

const changeCardType = (certificateType) => {
  const keys = ['age', 'birthday', 'sexCode']
  formOptions.value.map(o => {
    if (keys.indexOf(o.key) > -1) {
      o.props.disabled = type.value == '1'&&certificateType == '01'
    }
  })
}
const changeCardNumber = (certificateNo, config) => {
  const { certificateType } = dialogForm.value.formData
  if (certificateType != '01' || !idCardTool.isIdCard(certificateNo)) return
  dialogForm.value.formData.age = idCardTool.getAge(certificateNo)
  const gender = idCardTool.getSex(certificateNo)
  dialogForm.value.formData.sexCode = gender == '女' ? 'F' : 'M'
  dialogForm.value.formData.birthday = idCardTool.getBirth(certificateNo)
}

const openDialog = (type = '') => {
  dialogType.value = type
  dialogShow.value = true
}

const closeDialog = () => {
  dialogShow.value = false
}

const handleCancel = () => {
  dialogForm.value&&dialogForm.value.handleRefresh()
  closeDialog()
  dialogFormCurrent.value = null
}

const companyHolderRef = ref(null)
const handleConfirm = () => {
  if (dialogType.value == 'company-record') {
    const data = companyHolderRef.value.getCompanyData()
    tableData.value = [data]
    type.value == '2'
    handleCancel()
  }
  else {
     dialogForm.value.handleValidate(validate => {
      const o = { ...dialogForm.value.formData }
      if (validate) {
        tableData.value = [o]
        handleCancel()
      }
    })
  }  
}

const insert = () => {
  dialogFormCurrent.value = {
    id: dayjs().valueOf(),
    name: '',
    certificateType: defaultCardType,
    certificateNo: '',
    relationshipWithApplicant: '',
  }
  openDialog('insurant-insert')
}

const handleRecord =  (row) => {
  dialogFormCurrent.value = {}
  // type.value = 3
  openDialog('company-record')
}

const edit = (row) => {
  console.log(row);
  dialogFormCurrent.value = row
  openDialog()
}

const remove = (index) => {
  tableData.value.splice(index, 1)
}

const formData = reactive({
  
})

const getTaxNumber = () => {
  openDialog()
}

const changeType = (val) => {
  // type.value = val
  if (val == 0) {
    formOptions.value = config.editFormOptions.filter(o => !['birthday', 'sexCode', 'relationshipWithApplicant'].includes(o.key))
  }
  else if (val == 1) {
    formOptions.value = config.editFormOptions.slice(0, config.editFormOptions.length - 1)
  }
  tableData.value = []
  emits('policyHolderTypeChange', val)
}

const getData = async() => {
  // const { company, taxNumber } = formData
  // if (!company) {
  //   ElMessage.warning('请输入企业名称')
  //   return
  // }
  // if (!taxNumber) {
  //   ElMessage.warning('请输入税号')
  //   return
  // }
  // ElMessageBox.confirm(`确定要获取${company}的税号吗？`, '提示', {
  //  confirmButtonText: '确定',
  // })
  // if (type.value == '2') {
  //   if (tableData.value?.length < 1) {
  //     return  ElMessage.warning('请添加投保人信息')
  //   }
  //   return { ...tableData.value[0], personnelType: type.value }
  // }
  if (tableData.value?.length < 1) {
    return 
  }
  return { ...tableData.value[0], personnelType: type.value == '0'?'0':'1', id:'' }
}

const setPolicyHolder = (row) => {
  tableData.value = [row]
}

watch(type, (val) => {
  const column = formOptions.value.find(o => o.key == 'certificateType')
  column.options = val == 1 ? certificate_type : certificate_type_tuan
})

watch(() => props.dataSource, (val) => {
  if (!val) {
    return
  }
  type.value = val.personnelType||'2'
  tableData.value = [val]
}, { immediate: true })

defineExpose({
  getData, 
  setPolicyHolder
})

</script>